package zhangqi.com.asynctask;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;

import java.util.List;

public class ProgressBarTest extends Activity {

    private ProgressBar progressBar ;
    private MyAsyncTask2 mTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.progressbar);

        progressBar = (ProgressBar) findViewById(R.id.pg);
        mTask = new MyAsyncTask2();
        mTask.execute();//不需传值
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mTask!=null && mTask.getStatus() ==AsyncTask.Status.RUNNING){
            //cancel方法只是将对应的AsyncTask标记为cancel状态，并不是真正的取消线程的执行
            mTask.cancel(true);
        }
    }

    class MyAsyncTask2 extends AsyncTask<Void,Integer,Void>{

        @Override//模拟进度更新
        protected Void doInBackground(Void... params) {
            for(int i=0;i<100;i++){
                if(isCancelled()){
                    break;
                }
                publishProgress(i);

                try {
                    Thread.sleep(300);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //获取进度更新值
            Log.i("zhangqi","values[0]的值是"+values[0]);
            if(isCancelled()){
                return;
            }
            progressBar.setProgress(values[0]);
        }

    }
}
